package org.xebia.roo.addon.openshift;

import java.io.FileReader;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;

import org.springframework.roo.support.logging.HandlerUtils;

import com.openshift.express.internal.client.ApplicationInfo;
import com.openshift.express.internal.client.EmbeddableCartridgeInfo;

public class Util {

	private static final Logger LOGGER = HandlerUtils.getLogger(Util.class);

	private static final String EXPRESS_CONF = System.getProperty("user.home")
			+ "/.openshift/express.conf";

	private static final String GIT_URI_PATTERN = "ssh://{0}@{1}-{2}.{3}/~/git/{1}.git/";
	private static final String APPLICATION_URL_PATTERN = "https://{0}-{1}.{2}/";

	public static String getDefaultBaseUrl() {
		Properties conf = new Properties();
		try {
			conf.load(new FileReader(EXPRESS_CONF));
			LOGGER.info("Loaded OpenShift configuration from " + EXPRESS_CONF);
		} catch (Exception e) {
			// Swallow
		}

		String hostname = Util.unquote(conf.getProperty("libra_server"));

		if (hostname == null || hostname.trim().length() == 0) {
			return null;
		} else {
			return "https://".concat(hostname);
		}
	}

	static String unquote(String str) {
		if (str == null || str.length() < 2) {
			return str;
		}

		char a = str.charAt(0);
		char z = str.charAt(str.length() - 1);

		if (z == a && (z == '"' || z == '\'')) {
			return str.substring(1, str.length() - 1);
		} else {
			return str;
		}
	}

	public static String formatApplicationInfo(ApplicationInfo app,
			String namespace, String domain) {
		Map<String, String> attrs = new LinkedHashMap<String, String>();
		attrs.put("Framework", app.getCartridge().getName());
		attrs.put("Creation", app.getCreationTime().toString());
		attrs.put("UUID", app.getUuid());

		attrs.put(
				"Git URL",
				MessageFormat.format(GIT_URI_PATTERN, app.getUuid(),
						app.getName(), namespace, domain));
		attrs.put("Public URL", MessageFormat.format(APPLICATION_URL_PATTERN,
				app.getName(), namespace, domain));

		attrs.put("Embedded",
				formatEmbeddedCartridges(app.getEmbeddedCartridges()));

		int longest = 0;
		for (String key : attrs.keySet()) {
			longest = Math.max(longest, key.length());
		}

		final StringBuilder str = new StringBuilder();
		str.append(String.format(app.getName()));
		for (String key : attrs.keySet()) {
			str.append(String.format("\n  %s %s", pad(key + ":", longest),
					attrs.get(key)));
		}
		str.append("\n");
		return str.toString();
	}

	public static String formatEmbeddedCartridges(
			Collection<EmbeddableCartridgeInfo> cartridges) {
		if (cartridges.size() == 0) {
			return "None";
		}

		StringBuilder carts = new StringBuilder();

		for (EmbeddableCartridgeInfo info : cartridges) {
			if (carts.length() > 0) {
				carts.append(", ");
			}
			carts.append(info.getName());
		}

		return carts.toString();
	}

	private static String pad(String str, int len) {
		StringBuilder result = new StringBuilder(str);
		for (int i = 0; i < len - str.length() + 1; i++) {
			result.append(" ");
		}
		return result.toString();
	}
}
